﻿using DevExpress.ExpressApp.Security;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.BaseImpl.PermissionPolicy;
using DevExpress.Xpo;
using System.ComponentModel;

namespace EasyXaf.Sample.Module.BusinessObjects;

[MapInheritance(MapInheritanceType.ParentTable)]
[DefaultProperty(nameof(UserName))]
public class ApplicationUser : PermissionPolicyUser, ISecurityUserWithLoginInfo
{
    public ApplicationUser(Session session) : base(session) { }

    public Sex? Sex
    {
        get => GetPropertyValue<Sex?>(nameof(Sex));
        set => SetPropertyValue(nameof(Sex), value);
    }

    public int? Age
    {
        get => GetPropertyValue<int?>(nameof(Age));
        set => SetPropertyValue(nameof(Age), value);
    }

    public DateTime? Birthdate
    {
        get => GetPropertyValue<DateTime?>(nameof(Birthdate));
        set => SetPropertyValue(nameof(Birthdate), value);
    }

    public UserLevel? Level
    {
        get => GetPropertyValue<UserLevel?>(nameof(Level));
        set => SetPropertyValue(nameof(Level), value);
    }

    public string PhoneNumber
    {
        get => GetPropertyValue<string>(nameof(PhoneNumber));
        set => SetPropertyValue(nameof(PhoneNumber), value);
    }

    [ImageEditor]
    public byte[] Image
    {
        get => GetPropertyValue<byte[]>(nameof(Image));
        set => SetPropertyValue(nameof(Image), value);
    }

    [Association]
    public Department Department
    {
        get => GetPropertyValue<Department>(nameof(Department));
        set => SetPropertyValue(nameof(Department), value);
    }

    [Browsable(false)]
    [Aggregated, Association("User-LoginInfo")]
    public XPCollection<ApplicationUserLoginInfo> LoginInfo
    {
        get { return GetCollection<ApplicationUserLoginInfo>(nameof(LoginInfo)); }
    }

    IEnumerable<ISecurityUserLoginInfo> IOAuthSecurityUser.UserLogins => LoginInfo.OfType<ISecurityUserLoginInfo>();

    ISecurityUserLoginInfo ISecurityUserWithLoginInfo.CreateUserLoginInfo(string loginProviderName, string providerUserKey)
    {
        ApplicationUserLoginInfo result = new ApplicationUserLoginInfo(Session);
        result.LoginProviderName = loginProviderName;
        result.ProviderUserKey = providerUserKey;
        result.User = this;
        return result;
    }
}
